#include "cpu/exec/template-start.h"

#define instr add

static void do_execute(){
    DATA_TYPE result;
    if(ops_decoded.opcode == 0x05){
        op_dest->type = OP_TYPE_REG;
        op_dest->reg = R_EAX;
        op_dest->val = REG(op_dest->reg);
    }
    result = (DATA_TYPE)op_src->val + (DATA_TYPE)op_dest->val;
    //设置OF，有符号溢出，加数同号结果却变号
    if(op_src->val >> (DATA_BYTE*8 - 1) == op_dest->val >> (DATA_BYTE*8 - 1) && result >> (DATA_BYTE*8 - 1) != op_src->val >> (DATA_BYTE*8 - 1)){
        cpu.eflags.OF = 1;
    }
    else{
        cpu.eflags.OF = 0;
    }

    //设置CF，无符号溢出，结果没有大于两个加数
    if(!((DATA_TYPE)result >= (DATA_TYPE)op_dest->val && (DATA_TYPE)result >= (DATA_TYPE)op_src->val)){
        cpu.eflags.CF = 1;
    }
    else{
        cpu.eflags.CF = 0;
    }

    //设置ZF 
    if((DATA_TYPE)result == 0){
        cpu.eflags.ZF = 1;
    }
    else{
        cpu.eflags.ZF = 0;
    }

    //设置SF
    cpu.eflags.SF = result >> (DATA_BYTE * 8 -1);

    //设置PF，结果的低8位包含偶数个1
    uint32_t i;
    uint32_t k = 0;
    for(i = 0; i < 8; ++i){
        k += (result >> i) & 0x1;
    }
    if(k % 2 == 0){
        cpu.eflags.PF = 1;
    }
    else{
        cpu.eflags.PF = 0;
    }
    //设置AF，暂时就不设置了


    if(op_dest->type == OP_TYPE_REG){
        REG(op_dest->reg) = result;
    }
    else if(op_dest->type == OP_TYPE_MEM){
        MEM_W(op_dest->addr,result);
    }
    print_asm_template2();
}

make_instr_helper(i2rm)
make_instr_helper(i)
#if DATA_BYTE == 2 || DATA_BYTE == 4
make_instr_helper(si2rm)
#endif
make_instr_helper(r2rm)
make_instr_helper(rm2r)


#include "cpu/exec/template-end.h"